package com.lw.leetcode.binary.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * 611. 有效三角形的个数
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/4 9:29
 */
public class TriangleNumber {


    public static void main(String[] args) {
        TriangleNumber test = new TriangleNumber();
        int[] arr = {2, 2, 3, 4};
        int aa = test.triangleNumber(arr);

        System.out.println(aa);
    }

    public int triangleNumber(int[] nums) {
        Arrays.sort(nums);
        int length = nums.length - 1;
        int sum = 0;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                int t = nums[i] + nums[j];
                int n = find(nums, j, length, t);
                sum += (n - j);
            }
        }
        return sum;
    }

    private int find(int[] arr, int st, int end, int t) {
        while (st < end) {
            int m = st + ((end - st + 1) >> 1);
            if (arr[m] < t) {
                st = m;
            } else {
                end = m - 1;
            }
        }
        return st;
    }

}
